package ru.compft.common.utils;

import java.io.*;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * User: VVasiliev
 * Date: 25.05.12
 * Time: 9:35
 * Утилиты для разработки
 */
public class DevelopmentUtils {
//    private static File elapsedTimeFile = new File(GlobalConstants.USER_DIR + "/elapsedTime.txt");
    private static File elapsedTimeFile = new File(GlobalConstants.USER_DIR + "/tender_AS_DB_elapsedTime.txt");
    private static FileWriter writer;
    private static FileReader reader;
    private static final String START = "START";
    private static final String STOP = "STOP";
    private static final String COUNT = "COUNT";

    /**
     * Инициализация записи в файл
     */
    private static void initWriter() {
        checkFileExist();

        try {
            writer = new FileWriter(elapsedTimeFile, true);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Инициализация чтения из файла
     */
    private static void initReader() {
        checkFileExist();

        try {
            reader = new FileReader(elapsedTimeFile);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Проверяем наличие файла и создаем его при необходимости
     */
    private static void checkFileExist() {
        if (!elapsedTimeFile.exists()) {
            try {
                final boolean createResult = elapsedTimeFile.createNewFile();
                System.out.println("New file {" + elapsedTimeFile.getName() + "} was created with result: " + createResult);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    /**
     * Освобождение ресурсов
     */
    private static void destroy() {
        System.out.println("Process stopped.");
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Засекаем время начала работы разработки проекта
     */
    public static void startWork() {
        initWriter();
        writeCommand(START);
    }

    /**
     * Засекаем время окончания работы разработки проекта
     */
    public static void stopWork() {
        initWriter();
        writeCommand(STOP);
    }

    /**
     * Подсчитываем время затраченное на разработку
     */
    public static void countWork() {
        initReader();

        final BufferedReader br = new BufferedReader(reader);

        String strLine;
        long totalTime = 0;
        long startTime = 0;
        long stopTime = 0;
        try {
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                if ((strLine.startsWith(START) && startTime != 0) || (strLine.startsWith(STOP) && stopTime != 0))
                    throw new IllegalArgumentException("Two string begin with equals index " + strLine);

                int startIndex = strLine.indexOf(GlobalConstants.DOUBLE_DOT) + 1;
                final String substring = strLine.substring(startIndex);
                final Date date = DateTimeUtils.getStringAsDate(substring);

                if (strLine.startsWith(START)) {
                    startTime = date.getTime();
                } else if (strLine.startsWith(STOP)) {
                    stopTime = date.getTime();

                    // суммируем
                    totalTime += (stopTime - startTime);

                    // обнуляем время
                    startTime = 0;
                    stopTime = 0;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long days = TimeUnit.MILLISECONDS.toDays(totalTime); // общее время в днях
        long hours = TimeUnit.MILLISECONDS.toHours(totalTime);  // общее время в часах
        long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime); // общее время в минутах
        long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime); // общее время в секундах

        final String result1 = String.format(GlobalConstants.DD_HH_MM_SS_FORMAT,
                days,
                hours - TimeUnit.DAYS.toHours(days),
                minutes - TimeUnit.HOURS.toMinutes(hours),
                seconds - TimeUnit.MINUTES.toSeconds(minutes));

        final String result2 = String.format(GlobalConstants.HH_MM_SS_FORMAT,
                hours,
                minutes - TimeUnit.HOURS.toMinutes(hours),
                seconds - TimeUnit.MINUTES.toSeconds(minutes));

        long workDays = hours / 8;
        final String result3 = String.format(GlobalConstants.WORKDD_HH_MM_SS_FORMAT,
                workDays,
                hours - (workDays * 8),
                minutes - TimeUnit.HOURS.toMinutes(hours),
                seconds - TimeUnit.MINUTES.toSeconds(minutes));

        System.out.println("totalTime (HH:MM:SS) = " + result2);
        System.out.println("totalTime (DD HH:MM:SS) = " + result1);
        System.out.println("work Time (DD HH:MM:SS) = " + result3);
    }

    /**
     * Записываем команду с текущим временем в файл
     *
     * @param command
     */
    private static void writeCommand(String command) {
        try {
            writer.write(command + GlobalConstants.DOUBLE_DOT + DateTimeUtils.getCurrentDate() + GlobalConstants.EOL);
            System.out.println("New " + command + " record was appended!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.print("Input command(" + START + " or " + STOP + " or " + COUNT + "): ");

        String command = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try {
            command = reader.readLine().trim();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (START.equalsIgnoreCase(command) || STOP.equalsIgnoreCase(command) || COUNT.equalsIgnoreCase(command)) {
            if (START.equalsIgnoreCase(command)) {
                startWork();
            } else if (STOP.equalsIgnoreCase(command)) {
                stopWork();
            } else if (COUNT.equalsIgnoreCase(command)) {
                countWork();
            }
        } else {
            System.out.println("Unknown command = " + command);
        }

        destroy();
    }
}
